package com.situ.blog.controller;

import com.situ.blog.pojo.User;
import com.situ.blog.service.IUserService;
import com.situ.blog.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/getLoginPage")
    public String getLoginPage() {
        //soutm
        System.out.println("LoginController.getLoginPage");
        return "/WEB-INF/login.jsp";
    }

    // /login/login
    @RequestMapping("/login")
    @ResponseBody
    public JSONResult login(String name, String password, HttpSession session) {
        //JSONResult jsonResult = userService.login(name, password);
        //return jsonResult;
        User user = userService.login(name, password);

        if (user != null) {
            //把用户登录的信息放到Session
            session.setAttribute("user", user);

            return JSONResult.ok("登录成功", user);
        } else {
            return JSONResult.error("登录失败");
        }
        // return user != null ? JSONResult.ok("登录成功", user) : JSONResult.error("登录失败");
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();

        return "redirect:/login/getLoginPage";
    }
}
